<template>
  <view class="reviews-page">
    <!-- 页面标题 -->
    <view class="page-header">
      <text class="page-title">评价管理</text>
      <text class="page-subtitle">管理停车场的用户评价</text>
    </view>

    <!-- 筛选器 -->
    <view class="filter-section">
      <view class="filter-item">
        <text class="filter-label">状态筛选：</text>
        <picker mode="selector" :value="statusIndex" :range="statusOptions" @change="onStatusChange">
          <view class="picker-text">{{ statusOptions[statusIndex] }}</view>
        </picker>
      </view>
    </view>

    <!-- 评价列表 -->
    <view class="reviews-list" v-if="!loading">
      <view v-if="reviews.length === 0" class="empty-state">
        <text class="empty-text">暂无评价数据</text>
      </view>
      
      <view v-else>
        <view v-for="review in reviews" :key="review.id" class="review-item">
          <!-- 评价头部 -->
          <view class="review-header">
            <view class="user-info">
              <image 
                class="user-avatar" 
                :src="review.user_avatar || '/static/default-avatar.png'"
                mode="aspectFill"
              />
              <view class="user-details">
                <text class="user-name">{{ review.user_nickname || '匿名用户' }}</text>
                <text class="review-time">{{ formatDate(review.created_at) }}</text>
              </view>
            </view>
            
            <view class="review-rating">
              <view class="stars">
                <text v-for="i in 5" :key="i" 
                      class="star" 
                      :class="{ 'star-filled': i <= review.rating }">
                  ★
                </text>
              </view>
              <text class="rating-text">{{ review.rating }}.0分</text>
            </view>
          </view>

          <!-- 评价内容 -->
          <view class="review-content">
            <text class="comment-text">{{ review.comment || '用户未留言' }}</text>
          </view>

          <!-- 评价元信息 -->
          <view class="review-meta">
            <text class="order-info">订单号：{{ review.order_number }}</text>
            <view class="status-badge" :class="review.status">
              <text class="status-text">{{ review.status === 'visible' ? '显示中' : '已隐藏' }}</text>
            </view>
          </view>

          <!-- 管理员回复 -->
          <view v-if="review.replies && review.replies.length > 0" class="replies-section">
            <view v-for="reply in review.replies" :key="reply.id" class="reply-item">
              <view class="reply-header">
                <text class="reply-author">{{ reply.reply_user_nickname || '管理员' }}</text>
                <text class="reply-time">{{ formatDate(reply.created_at) }}</text>
              </view>
              <text class="reply-content">{{ reply.content }}</text>
            </view>
          </view>

          <!-- 操作按钮 -->
          <view class="review-actions">
            <button 
              class="action-btn status-btn"
              :class="review.status === 'visible' ? 'hide-btn' : 'show-btn'"
              @click="toggleReviewStatus(review)"
            >
              {{ review.status === 'visible' ? '隐藏' : '显示' }}
            </button>
            <button class="action-btn reply-btn" @click="showReplyDialog(review)">
              回复
            </button>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-state">
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 分页 -->
    <view v-if="reviews.length > 0" class="pagination">
      <button 
        class="page-btn" 
        :disabled="currentPage <= 1"
        @click="loadPreviousPage"
      >
        上一页
      </button>
      <text class="page-info">{{ currentPage }} / {{ totalPages }}</text>
      <button 
        class="page-btn" 
        :disabled="currentPage >= totalPages"
        @click="loadNextPage"
      >
        下一页
      </button>
    </view>

    <!-- 回复对话框 -->
    <view class="reply-modal" v-if="showReplyModal" @click="hideReplyDialog">
      <view class="reply-dialog" @click.stop>
        <view class="dialog-header">
          <text class="dialog-title">回复评价</text>
          <text class="close-btn" @click="hideReplyDialog">×</text>
        </view>
        
        <view class="dialog-content">
          <view class="original-review" v-if="currentReview">
            <view class="review-summary">
              <view class="user-info">
                <text class="user-name">{{ currentReview.user_nickname || '匿名用户' }}</text>
                <view class="stars">
                  <text v-for="i in 5" :key="i" 
                        class="star small" 
                        :class="{ 'star-filled': i <= currentReview.rating }">
                    ★
                  </text>
                </view>
              </view>
              <text class="comment-text">{{ currentReview.comment || '用户未留言' }}</text>
            </view>
          </view>
          
          <view class="reply-form">
            <text class="form-label">回复内容</text>
            <textarea 
              class="reply-input"
              v-model="replyContent"
              placeholder="请输入回复内容..."
              maxlength="500"
              :show-confirm-bar="false"
            />
            <text class="char-count">{{ replyContent.length }}/500</text>
          </view>
        </view>
        
        <view class="dialog-footer">
          <button class="dialog-btn cancel-btn" @click="hideReplyDialog">取消</button>
          <button 
            class="dialog-btn submit-btn" 
            :disabled="!replyContent.trim() || submittingReply"
            @click="submitReply"
          >
            {{ submittingReply ? '提交中...' : '发送回复' }}
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { get, put, post } from '../../utils/request.js'

// 响应式数据
const loading = ref<boolean>(false)
const reviews = ref<any[]>([])
const currentPage = ref<number>(1)
const pageSize = ref<number>(10)
const totalPages = ref<number>(1)
const totalCount = ref<number>(0)

// 筛选相关
const statusIndex = ref<number>(0)
const statusOptions = ['全部', '显示中', '已隐藏']
const statusValues = ['', 'visible', 'hidden']

// 回复对话框相关
const showReplyModal = ref<boolean>(false)
const currentReview = ref<any>(null)
const replyContent = ref<string>('')
const submittingReply = ref<boolean>(false)

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 状态筛选改变
const onStatusChange = (e: any) => {
  statusIndex.value = e.detail.value
  currentPage.value = 1
  loadReviews()
}

// 加载评价列表
const loadReviews = async () => {
  loading.value = true
  
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      status: statusValues[statusIndex.value]
    }
    
    const response = await get('/api/parking-operator/reviews', params, { loading: false })
    
    reviews.value = response.data.list
    totalCount.value = response.data.total
    totalPages.value = response.data.totalPages
  } catch (error) {
    console.error('获取评价列表失败:', error)
    uni.showToast({
      title: '获取评价列表失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 切换评价状态
const toggleReviewStatus = async (review: any) => {
  const newStatus = review.status === 'visible' ? 'hidden' : 'visible'
  const actionText = newStatus === 'visible' ? '显示' : '隐藏'
  
  try {
    await put(`/api/parking-operator/reviews/${review.id}/status`, { status: newStatus })
    
    review.status = newStatus
    uni.showToast({
      title: `评价已${actionText}`,
      icon: 'success'
    })
  } catch (error) {
    console.error('更新评价状态失败:', error)
    uni.showToast({
      title: '操作失败，请重试',
      icon: 'none'
    })
  }
}

// 显示回复对话框
const showReplyDialog = (review: any) => {
  currentReview.value = review
  replyContent.value = ''
  showReplyModal.value = true
}

// 隐藏回复对话框
const hideReplyDialog = () => {
  showReplyModal.value = false
  currentReview.value = null
  replyContent.value = ''
}

// 提交回复
const submitReply = async () => {
  if (!replyContent.value.trim()) {
    uni.showToast({
      title: '请输入回复内容',
      icon: 'none'
    })
    return
  }

  submittingReply.value = true

  try {
    await post(`/api/parking-operator/reviews/${currentReview.value.id}/reply`, { 
      content: replyContent.value.trim() 
    })

    uni.showToast({
      title: '回复成功',
      icon: 'success'
    })
    
    hideReplyDialog()
    
    // 重新加载评价列表
    setTimeout(() => {
      loadReviews()
    }, 1000)
  } catch (error) {
    console.error('回复失败:', error)
    uni.showToast({
      title: '回复失败，请重试',
      icon: 'none'
    })
  } finally {
    submittingReply.value = false
  }
}

// 加载上一页
const loadPreviousPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
    loadReviews()
  }
}

// 加载下一页
const loadNextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    loadReviews()
  }
}

// 页面加载时获取数据
onMounted(() => {
  loadReviews()
})
</script>

<style scoped>
.reviews-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding: 20rpx;
}

.page-header {
  background-color: #fff;
  padding: 40rpx 30rpx;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  text-align: center;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
}

.page-subtitle {
  font-size: 28rpx;
  color: #666;
}

.filter-section {
  background-color: #fff;
  padding: 30rpx;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
}

.filter-item {
  display: flex;
  align-items: center;
}

.filter-label {
  font-size: 28rpx;
  color: #333;
  margin-right: 20rpx;
}

.picker-text {
  font-size: 28rpx;
  color: #007aff;
  padding: 10rpx 20rpx;
  border: 1rpx solid #007aff;
  border-radius: 6rpx;
}

.reviews-list {
  margin-bottom: 20rpx;
}

.empty-state {
  background-color: #fff;
  padding: 100rpx 30rpx;
  border-radius: 12rpx;
  text-align: center;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

.review-item {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.review-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20rpx;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  margin-right: 20rpx;
}

.user-details {
  display: flex;
  flex-direction: column;
}

.user-name {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
  margin-bottom: 8rpx;
}

.review-time {
  font-size: 24rpx;
  color: #999;
}

.review-rating {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.stars {
  display: flex;
  margin-bottom: 8rpx;
}

.star {
  font-size: 28rpx;
  color: #ddd;
  margin-left: 4rpx;
}

.star.small {
  font-size: 24rpx;
}

.star-filled {
  color: #ffa500;
}

.rating-text {
  font-size: 24rpx;
  color: #666;
}

.review-content {
  margin-bottom: 20rpx;
}

.comment-text {
  font-size: 28rpx;
  color: #333;
  line-height: 1.6;
}

.review-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  padding-top: 20rpx;
  border-top: 1rpx solid #f0f0f0;
}

.order-info {
  font-size: 24rpx;
  color: #666;
}

.status-badge {
  padding: 8rpx 16rpx;
  border-radius: 12rpx;
  font-size: 22rpx;
}

.status-badge.visible .status-text {
  color: #52c41a;
  background-color: #f6ffed;
}

.status-badge.hidden .status-text {
  color: #fa8c16;
  background-color: #fff7e6;
}

.replies-section {
  background-color: #f8f9fa;
  border-radius: 8rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.reply-item {
  margin-bottom: 16rpx;
}

.reply-item:last-child {
  margin-bottom: 0;
}

.reply-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8rpx;
}

.reply-author {
  font-size: 24rpx;
  color: #007aff;
  font-weight: bold;
}

.reply-time {
  font-size: 22rpx;
  color: #999;
}

.reply-content {
  font-size: 26rpx;
  color: #333;
  line-height: 1.5;
}

.review-actions {
  display: flex;
  gap: 20rpx;
}

.action-btn {
  flex: 1;
  padding: 20rpx 0;
  border-radius: 8rpx;
  font-size: 26rpx;
  font-weight: bold;
  border: 1rpx solid;
}

.status-btn.hide-btn {
  background-color: #fff;
  color: #fa8c16;
  border-color: #fa8c16;
}

.status-btn.show-btn {
  background-color: #fff;
  color: #52c41a;
  border-color: #52c41a;
}

.reply-btn {
  background-color: #007aff;
  color: #fff;
  border-color: #007aff;
}

.loading-state {
  background-color: #fff;
  padding: 100rpx 30rpx;
  border-radius: 12rpx;
  text-align: center;
}

.loading-text {
  font-size: 28rpx;
  color: #999;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #fff;
  padding: 30rpx;
  border-radius: 12rpx;
  gap: 30rpx;
}

.page-btn {
  padding: 16rpx 32rpx;
  background-color: #007aff;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  font-size: 26rpx;
}

.page-btn:disabled {
  background-color: #ddd;
  color: #999;
}

.page-info {
  font-size: 26rpx;
  color: #333;
}

/* 回复对话框样式 */
.reply-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.reply-dialog {
  background-color: #fff;
  border-radius: 16rpx;
  width: 90%;
  max-width: 600rpx;
  max-height: 80vh;
  overflow: hidden;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.dialog-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.close-btn {
  font-size: 40rpx;
  color: #999;
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.dialog-content {
  padding: 30rpx;
  max-height: 60vh;
  overflow-y: auto;
}

.original-review {
  margin-bottom: 30rpx;
  padding: 20rpx;
  background-color: #f8f9fa;
  border-radius: 8rpx;
}

.review-summary .user-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12rpx;
}

.reply-form {
  margin-bottom: 20rpx;
}

.form-label {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 16rpx;
  display: block;
}

.reply-input {
  width: 100%;
  min-height: 120rpx;
  padding: 20rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  font-size: 28rpx;
  line-height: 1.5;
  margin-bottom: 10rpx;
  box-sizing: border-box;
}

.char-count {
  text-align: right;
  font-size: 24rpx;
  color: #999;
}

.dialog-footer {
  display: flex;
  padding: 20rpx 30rpx 30rpx;
  gap: 20rpx;
}

.dialog-btn {
  flex: 1;
  padding: 24rpx 0;
  border-radius: 8rpx;
  font-size: 28rpx;
  font-weight: bold;
  border: 1rpx solid;
}

.dialog-btn.cancel-btn {
  background-color: #fff;
  color: #666;
  border-color: #ddd;
}

.dialog-btn.submit-btn {
  background-color: #007aff;
  color: #fff;
  border-color: #007aff;
}

.dialog-btn:disabled {
  opacity: 0.5;
}
</style>